package com.example.learnandroid;

import java.util.ArrayList;
import java.util.List;

import com.stay.gif.GifEncoder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class PreviewGIF extends Activity implements Runnable{
	SeekBar seekbar;
	Button make_gif;
	ArrayList<Bitmap> lBitmap;
	Worker1 worker1;
	int progressSeekBar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.preview_gif);
		setListenerOnSeekBar();
		setListenerOnButton();
		lBitmap = Images.listImage;
		worker1 = new Worker1();
		worker1.start();
		
		
	}
	private void setListenerOnButton(){
		make_gif = (Button) findViewById(R.id.make_gif);
		make_gif.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				makeGIF();
				
			}
		});
	}
	private void setListenerOnSeekBar(){
		seekbar = (SeekBar) findViewById(R.id.seek_preview);
		seekbar.setProgress(50);
		seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
 
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
            	progressSeekBar = progress;
            }
 
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }
 
            public void onStopTrackingTouch(SeekBar seekBar) {
                
            }
        });
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(!worker1.isInterrupted()){
			worker1.interrupt();
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if(!worker1.isInterrupted()){
			worker1.interrupt();
		}
	}
	
	public class Worker1 extends Thread{
		public void run(){
			// TODO Auto-generated method stub
			int i=0;
			final ImageView image = (ImageView) findViewById(R.id.gif_preview);
			while(!Thread.currentThread().isInterrupted()){
				final int image_index = i % 20;
				//final int width_pixel = dpToPx(300);
				//final int height_pixel = (int)((float)width_pixel*(240f/320f));
				//System.out.println(width_pixel);
				image.post(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Bitmap bm = lBitmap.get(image_index);
						int width = bm.getWidth();
						int height = bm.getHeight();
						//Bitmap bm_scaled = getResizedBitmap(bm,width_pixel,height_pixel);
						//Bitmap bm2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
						//int[] pixels = new int[width*height];
						//bm.getPixels(pixels, 0, width, 0, 0, width, height);
						//bm2.setPixels(pixels, 0, width, 0, 0, width, height);
						image.setImageBitmap(bm);
					}
				});
				
				try {
					Thread.sleep(250 - progressSeekBar);
				} catch (InterruptedException e) { 
					// TODO Auto-generated catch block
					e.printStackTrace();
					Thread.currentThread().interrupt();
				}
				i++;
			}
			
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		int i=0;
		final ImageView image = (ImageView) findViewById(R.id.gif_preview);
		while(!Thread.currentThread().isInterrupted()){
			final int image_index = i % 20;
			image.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					image.setImageBitmap(lBitmap.get(image_index));
				}
			});
			
			try {
				Thread.sleep(100 - progressSeekBar);
			} catch (InterruptedException e) { 
				// TODO Auto-generated catch block
				e.printStackTrace();
				Thread.currentThread().interrupt();
			}
			i++;
		}
	}

	private void makeGIF(){
		int width = 320;
		int height = 240;
		GifEncoder giflen = new GifEncoder();
		int state =	giflen.init("/sdcard/gif/output.gif", width, height, 256, 10, 20);
		if (state != 0) {
			Log.e("TAG","Init gifflen error");
			return;
		}
		int [] pixels = new int[width * height];
		for(int i=0;i<lBitmap.size();i++){
			lBitmap.get(i).getPixels(pixels, 0, width, 0, 0, width, height);
			giflen.addFrame(pixels);
		}
		giflen.close();
		Toast.makeText(PreviewGIF.this, 
    			"Finish :)", 
    			Toast.LENGTH_SHORT).show();
	}
	
	

	private int dpToPx(int dp)
	{
	    float density = getApplicationContext().getResources().getDisplayMetrics().density;
	    return Math.round((float)dp * density);
	}
	
	private Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
		 
		int width = bm.getWidth();
		 
		int height = bm.getHeight();
		 
		float scaleWidth = ((float) newWidth) / width;
		 
		float scaleHeight = ((float) newHeight) / height;
		 
		// CREATE A MATRIX FOR THE MANIPULATION
		 
		Matrix matrix = new Matrix();
		 
		// RESIZE THE BIT MAP
		 
		matrix.postScale(scaleWidth, scaleHeight);
		 
		// RECREATE THE NEW BITMAP
		 
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
		 
		return resizedBitmap;
		 
	}
}
